package com.testflow.hyh.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.nio.charset.Charset;

@Slf4j
public class HttpUtil {

    /**
     * token标识
     */
    public static String accTokenName = null;
    /**
     * token参数
     */
    public static String accToken = null;

    private static CloseableHttpClient httpClient;

    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(100);
        cm.setDefaultMaxPerRoute(20);
        cm.setDefaultMaxPerRoute(50);
        httpClient = HttpClients.custom().setConnectionManager(cm).build();
    }

    /**
     * 通用Post请求
     * @param url
     * @param jsonString
     * @return
     */
    public static String commonPostRequest(String url,String jsonString) {
        CloseableHttpResponse response = null;
        BufferedReader in = null;
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
            httpPost.setConfig(requestConfig);
            httpPost.setConfig(requestConfig);
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            if(accTokenName!=null&&accToken!=null){
                httpPost.setHeader(accTokenName,accToken);
            }
            if (jsonString != null) {
                httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
            }
            response = httpClient.execute(httpPost);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            result = sb.toString();
        }catch (ConnectException conn){
            conn.printStackTrace();
            log.error("服务端已关闭,链接已超时!");
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 通用Delete请求
     *
     * @param url
     * @param sn
     * @return
     */
    public static String commonDeleteRequest(String url, String sn) {
        CloseableHttpResponse response = null;
        BufferedReader in = null;
        String result = "";
        try {
            HttpDelete delete = new HttpDelete(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
            delete.setConfig(requestConfig);
            delete.setConfig(requestConfig);
            delete.addHeader("Content-type", "application/json; charset=utf-8");
            delete.setHeader("Accept", "application/json");
            if(accTokenName!=null&&accToken!=null){
                delete.setHeader(accTokenName,accToken);
            }
            response = httpClient.execute(delete);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            result = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 通用GET请求
     * @param url
     * @param sn
     * @return
     */
    public static String commonGetRequest(String url, String sn) {
        CloseableHttpResponse response = null;
        BufferedReader in = null;
        String result = "";
        try {
            HttpGet get = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
            get.setConfig(requestConfig);
            get.setConfig(requestConfig);
            get.addHeader("Content-type", "application/json; charset=utf-8");
            get.setHeader("Accept", "application/json");
            if(accTokenName!=null&&accToken!=null){
                get.setHeader(accTokenName,accToken);
            }
            response = httpClient.execute(get);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            result = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 通用PUT请求
     * @param url
     * @param sn
     * @return
     */
    public static String commonPutRequest(String url, String sn,String jsonString) {
        CloseableHttpResponse response = null;
        BufferedReader in = null;
        String result = "";
        try {
            HttpPut put = new HttpPut(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
            put.setConfig(requestConfig);
            put.setConfig(requestConfig);
            put.addHeader("Content-type", "application/json; charset=utf-8");
            put.setHeader("Accept", "application/json");
            if(accTokenName!=null&&accToken!=null){
                put.setHeader(accTokenName,accToken);
            }
            if (jsonString != null) {
                put.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
            }
            response = httpClient.execute(put);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            result = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
